<!-- 五千米学校圈 -->
<template>
	<zh-app style="font-family: '阿里巴巴普惠体'">
		<!-- 导航栏 -->
		<zh-navbar title="15公里学校圈" color="#85a5ff" linear="right" :hideHome="true" />
		<!-- 地图 -->
		<view id="map_container">
			<zh-sheet class="current-position" :margin="[0, 0]" :padding="[20, 20]">
				<zh-text :label="'当前位置：' + data.currentPosition" :fontSize="24"></zh-text>
			</zh-sheet>
		</view>
		<!-- 学校列表 -->
		<view class="sch-arr">
			<view class="flex-bothends">
				<!-- 查询条件操作栏 -->
				<view class="flex-bothends">
					<zh-text label="学段筛选" :fontSize="28" style="margin-left: 20rpx"></zh-text>
					<zh-radio-group model="button" v-model="data.schoolCategory" @change="onChange">
						<zh-radio :value="1" label="幼儿园"></zh-radio>
						<zh-radio :value="2" label="小学"></zh-radio>
						<zh-radio :value="3" label="初中"></zh-radio>
					</zh-radio-group>
				</view>
				<view class="flex-bothends">
					<zh-text label="是否住校" :fontSize="28"></zh-text>
					<zh-switch
						size="mini"
						:followTheme="false"
						:defaultValue="data.configType"
						:margin="[12, 0]"
						@change="onSwitch"
					></zh-switch>
				</view>
			</view>
			<!-- 列表 -->
			<view class="arr">
				<view class="item flex-bothends" v-for="(item, index) in data.schArr" :key="index">
					<view class="block flex-bothends">
						<tm-icon name="tmicon-ios-bookmarks" :fontSize="48"></tm-icon>
						<view class="right-txt flex-col-bet-start">
							<zh-text :label="item.schoolName" :fontSize="28"></zh-text>
							<zh-text :label="'距离：' + item.distance + '米'" :fontSize="28"></zh-text>
						</view>
					</view>
					<view class="block">
						<zh-button
							:margin="[0]"
							:shadow="0"
							text
							size="mini"
							:width="160"
							outlined
							label="我要报名"
							@tap="enroll(item)"
						></zh-button>
						<view class="flex-bothends">
							<zh-text label="热度：" :fontSize="28"></zh-text>
							<view class="hot" :style="{ backgroundColor: item.hotColor }"></view>
						</view>
					</view>
				</view>
			</view>
		</view>
		<!-- 底部学生选择栏 -->
		<zh-action-menu rangKey="fullName" v-model="data.showFlag" :list="data.stuArr" @change="gotoBm(data.schoolId)"></zh-action-menu>
		<!-- 全局消息提示 -->
		<zh-message ref="messageRef" :duration="2000"></zh-message>
		<zh-modal
			title="系统提示"
			:content="data.error.message"
			cancelText="取消"
			:okText="data.error.code === 1 ? '确认' : '前往'"
			:overlayClick="false"
			v-model:show="data.showError"
			@ok="onOk"
			@cancel="onCancel"
		></zh-modal>
	</zh-app>
</template>
<script lang="ts" setup>
	import { ref, reactive, shallowRef } from 'vue'
	import { onLoad } from '@dcloudio/uni-app'
	import AMapLoader from '@amap/amap-jsapi-loader'

	// ------------------接收传入参数(组件)-------------------

	// ------------------变量区------------------------------
	// 全局提示对象
	const messageRef = ref()
	// 地图对象
	let map = shallowRef(null)
	// 主数据
const data = reactive({
    // 学校id 
    schoolId: '',
		// 学校数组
		schArr: [] as Array<any>,
		// 当前选择的学段
		schoolCategory: 1,
		// 是否住校
		configType: false,
		// 当前位置
		currentPosition: '---',
		// 标点数组
		pointArr: [] as Array<any>,
		// 经纬度
		lngLat: [] as Array<any>,
		// 底部学生选择栏显示标记
		showFlag: false,
		// 学生列表
		stuArr: [],
		// 当前年份
		year: new Date().getFullYear(),
		error: {} as any,
		showError: false,
	})

	// ------------------方法区------------------------------
	// 义务段报名中处理
	const bmYw = () => {
		const params = { schoolCategory: data.schoolCategory }
		$api.common.send
			.post('eduStudentEnroll0023', params)
			.then((res: any) => {
				data.stuArr = res.result
				data.showFlag = true
			})
			.catch((err: any) => {
				console.log('err = ', err)
				openError(err)
			})
	}
	const openError = (error: any) => {
		data.error = error
		if (error.code > 0) {
			data.showError = true
		}
	}
	const onOk = () => {
		data.showError = false
		if (data.error.code === 2) {
			//前往我的报名
			$router.replace('/pages/edu/enroll/myEnroll', {})
		} else if (data.error.code === 3) {
			//前往准新生登记
			$router.replace('/pages/edu/newStuRegister/newStuRegister', {})
		}
	}
	const onCancel = () => {
		//关闭页面
		data.showError = false
	}
	// 报名
	const enroll = async (item: any) => {
		uni.$tm.u.throttle(async () => {
			// 判断是否学生
			const studentRet = await $api.common.send.post('eduStudentEnroll0007', {})
			if (studentRet.result) {
				const messageData: any = {}
				messageData.model = 'warn'
				messageData.text = '学生账号不能报名！请登录家长浙里办账号进行报名！'
				messageRef.value.show(messageData)
				return
      }
      data.schoolId = item.schoolId || ''
			// 判断是否在业务期范围内
			if (data.schoolCategory === 1) {
				// 幼儿园
				checkOp('1', item)
			} else {
				// 义务段
				checkOp('2', item)
			}
		}, 2000)
	}
	// 业务期判断
	const checkOp = (classify: String, item: any) => {
		if (classify == '1') {
			const params = { classify: classify, areaCode: '330783', operating: 'YRY001' }
			$api.common.send.post('OperationCache0003', params).then((res: any) => {
				let result = res.result
				if (result && result.flag) {
					// 跳转到幼儿园报名页
					gotoNursery(item.schoolId)
				} else {
					if (result.type === '1') {
						let messageData: any = {}
						messageData.model = 'disabled'
						messageData.text = result.messagePrompts
						messageRef.value.show(messageData)
						return
					} else if (result.type === '2') {
						let messageData: any = {}
						messageData.model = 'disabled'
						messageData.text = result.messageTip
						messageRef.value.show(messageData)
						return
					} else {
						let messageData: any = {}
						messageData.model = 'disabled'
						messageData.text = data.year + '年度幼儿园招生报名工作尚未开始！'
						messageRef.value.show(messageData)
						return
					}
				}
			})
		} else {
			// 义务段
			const params = { classify: classify, areaCode: '330783' }
			$api.common.send.post('OperationCache0001', params).then((res: any) => {
				let result = res.result
				if (result && result.operation) {
					let eduOperation: any = result.operation
					let YW002: any = {} //正式报名 第一轮
					let YW022: any = {} //补报 第二轮
					let YW010: any = {} //抢报 第三轮
					if (eduOperation) {
						YW002 = eduOperation.YW002
						YW022 = eduOperation.YW022
						YW010 = eduOperation.YW010
						if (YW002.flag || YW022.flag || YW010.flag) {
							// 报名中
							bmYw()
						} else {
							if (YW002.type === '1') {
								let messageData: any = {}
								messageData.model = 'disabled'
								messageData.text = YW002.messagePrompts || data.year + '年度义务教育段招生报名工作尚未开始！'
								messageRef.value.show(messageData)
								return
							} else if (YW002.type === '3') {
								let messageData: any = {}
								messageData.model = 'warn'
								messageData.text = data.year + '年度义务教育段招生报名工作尚未开始！'
								messageRef.value.show(messageData)
								return
							} else {
								if (YW022.type === '1') {
									let messageData: any = {}
									messageData.model = 'disabled'
									messageData.text = YW022.messagePrompts || data.year + '年度义务教育段招生补报工作尚未开始！'
									messageRef.value.show(messageData)
									return
								} else if (YW022.type === '3') {
									let messageData: any = {}
									messageData.model = 'warn'
									messageData.text = YW002.messageTip || data.year + '年度义务教育段招生报名已结束！'
									messageRef.value.show(messageData)
									return
								} else {
									if (YW010.type === '1') {
										let messageData: any = {}
										messageData.model = 'disabled'
										messageData.text = YW010.messagePrompts || data.year + '年度义务教育段招生第三轮报名尚未开始！'
										messageRef.value.show(messageData)
										return
									} else if (YW010.type === '3') {
										let messageData: any = {}
										messageData.model = 'warn'
										messageData.text = YW022.messageTip || data.year + '年度义务教育段招生报名已结束！'
										messageRef.value.show(messageData)
										return
									} else {
										let messageData: any = {}
										messageData.model = 'warn'
										messageData.text = YW010.messageTip || data.year + '年度义务教育段招生报名已结束！'
										messageRef.value.show(messageData)
										return
									}
								}
							}
						}
					} else {
						let messageData: any = {}
						messageData.model = 'warn'
						messageData.text = data.year + '年度义务教育段招生报名工作尚未开始！'
						messageRef.value.show(messageData)
						return
					}
				} else {
					let messageData: any = {}
					messageData.model = 'warn'
					messageData.text = data.year + '年度义务教育段招生报名工作尚未开始！'
					messageRef.value.show(messageData)
					return
				}
			})
		}
	}
	// 跳转至小学初中报名页
	const gotoBm = (item: any) => {
		$router.push('/pages/edu/enroll/enrollForm', {
			studentEnrollPreId: item.studentEnrollPreId,
			schoolId: item.schoolId,
		})
	}
	// 跳转至幼儿园学校选择页
	const gotoNursery = (schoolId: string) => {
		$router.push('/pages/edu/enroll/nurseryEnroll/nurseryEnroll', {
			schoolId: schoolId,
		})
	}
	// 开关状态改变的回调
	const onSwitch = (val: boolean) => {
		data.configType = val
		getSchArray()
	}
	// 单选框选择的回调
	const onChange = (val: number) => {
		data.schoolCategory = val
		getSchArray()
	}
	// 获取当前五千米内的学校列表
	const getSchArray = () => {
		const params: any = {
			longitude: data.lngLat[0],
			latitude: data.lngLat[1],
			raidus: 5000,
			schoolCategory: data.schoolCategory,
			configType: data.configType ? 1 : 0,
		}
		$api.common.send.post('EduAnalysisXq0035', params).then((res: any) => {
			data.schArr = []
			const result: any = res.result
			for (const item of result) {
				if (item.stuRsTjList.length !== 0) {
					// 报名人数
					const enrollNum = Number(item.stuRsTjList[0].sigNum)
					// 计划人数
					const planNum = Number(item.stuRsTjList[0].plaNum)
					// 比率
					let rate = Math.round((enrollNum / planNum) * 100) / 100
					console.log('rate = ', rate)
					if (rate >= 1) {
						item.hotColor = '#DD001B'
					} else if (rate >= 0.9) {
						item.hotColor = '#D8B971'
					} else {
						item.hotColor = '#82C08E'
					}
				}
			}
			data.schArr = result
		})
	}
	// 获取学校标点数据
	const getSchPoint = () => {
		const params: any = {
			areaCode: '330783',
		}
		$api.common.send.post('eduschool0008', params).then((res: any) => {
			data.pointArr = res.result
			initMap()
		})
	}
	// 地图初始化
	const initMap = () => {
		window._AMapSecurityConfig = {
			securityJsCode: '5a2f63e828dc36e3239ffa80ac66cc0d', // 安全密匙
		}
		AMapLoader.load({
			key: '1e35117539e6b0e35fc219fe9d6c0644', // Web端开发者Key
			version: '2.0', // JSAPI 的版本，缺省时默认为 1.4.15
			plugins: ['AMap.Geolocation', 'AMap.Geocoder'], // 插件列表
		})
			.then((AMap) => {
				// 实例化地图
				map = new AMap.Map('map_container', {
					//地图容器id
					viewMode: '3D', // 是否为3D地图模式
					center: [120.24179, 29.290158], //中心点位置
					zoom: 15,
				})
				// 添加标点
				addMarker(AMap, map, data.pointArr)
				// 获取当前位置
				getLocation(AMap, map)
			})
			.catch((err) => {
				console.log(err)
			})
	}
	// 逆地理编码
	const regeoCode = (AMap: any, lnglat: Array<any>) => {
		const geocoder = new AMap.Geocoder({
			radius: 1000,
			extensions: 'all',
		})
		geocoder.getAddress(lnglat, function (status, result) {
			status === 'complete' && result.regeocode
				? (data.currentPosition = result.regeocode.formattedAddress)
				: console.log('根据经纬度查询地址失败')
		})
	}
	// 获取定位信息
	const getLocation = (AMap: any, map: any) => {
		map.plugin('AMap.Geolocation', function () {
			let geolocation = new AMap.Geolocation({
				// 是否使用高精度定位，默认:true
				enableHighAccuracy: true,
				// 超过5秒后停止定位，默认：无穷大
				timeout: 5000,
				// 定位按钮的停靠位置的偏移量
				offset: [10, 20],
				//  定位成功后调整地图视野范围使定位位置及精度范围视野内可见，默认：false
				zoomToAccuracy: true,
				//  定位按钮的排放位置,  RB表示右下
				position: 'RB',
			})
			map.addControl(geolocation)
			geolocation.getCurrentPosition(function (status: any, result: any) {
				status == 'complete' ? onComplete(result) : onError(result)
			})
			// 定位成功
			function onComplete(val: any) {
				data.lngLat = [val.position.lng, val.position.lat]
				// 逆地理编码
				regeoCode(AMap, data.lngLat)
				// 获取当前15公里内的学校列表
				getSchArray()
			}
			// 定位出错
			function onError(data: any) {
				console.log('onError = ', data)
			}
		})
	}
	// 添加标点
	const addMarker = (AMap: any, map: any, pointArr: Array<any>) => {
		for (let point of pointArr) {
			// 添加标点
			const marker = new AMap.Marker({
				position: [point.longitude, point.latitude],
				// 偏移量
				offset: new AMap.Pixel(0, 0),
				title: point.schoolName,
				map: map,
			})
			// 文本标注
			marker.setLabel({
				offset: new AMap.Pixel(0, 30), // 文本标注偏移量
				content:
					'<div style="background:blue;font-weight:700;color:#ffffff;font-size:18px;line-height:20px;padding: 5px">' +
					point.schoolName +
					'</div>', // 文本标注内容
				direction: 'center', // 文本标注方位
			})
		}
	}
	// ------------------钩子函数----------------------------
	// 初始化
	onLoad((options: any) => {
		console.log('options = ', options)
		initMap()
	})
</script>
<style lang="scss" scoped>
	#map_container {
		padding: 0;
		margin: 0;
		width: 750rpx;
		height: 750rpx;
		z-index: 0;
		position: relative;
	}

	.current-position {
		width: 750rpx;
		height: 80rpx;
		background-color: white;
		z-index: 999;
		font-weight: 600;
		line-height: 80rpx;
		position: absolute;
		top: 0;
		left: 0;
	}

	.sch-arr {
		width: 750rpx;
		height: 800rpx;
		background-color: white;
		.arr {
			height: 700rpx;
			overflow: scroll;

			.item {
				width: 710rpx;
				padding: 10rpx 20rpx;

				.block {
					height: 80rpx;

					.right-txt {
						margin-left: 10rpx;
					}
				}
				.hot {
					width: 80rpx;
					height: 30rpx;
				}
			}
		}
	}
</style>
